package service

import (
	"os"

	"github.com/sirupsen/logrus"
	cdn "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/cdn/v20180606"
	"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common"
	"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/errors"
	"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/profile"
)

// 创建CDN客户端
func TencentCdnClient() *cdn.Client {
	credential := common.NewCredential(
		os.Getenv("TENCENT_CLOUD_API_KEY"),
		os.Getenv("TENCENT_CLOUD_API_SECRET"),
	)
	cpf := profile.NewClientProfile()
	cpf.HttpProfile.Endpoint = "cdn.tencentcloudapi.com"
	client, err := cdn.NewClient(credential, "", cpf)
	if err != nil {
		logrus.WithFields(logrus.Fields{
			"error": err.Error(),
		}).Fatal("Failed to create Tencent CDN client")
	}
	return client
}

// PreHostUrls 预热CDN URL
func PreHostUrls(urls []string) error {
	client := TencentCdnClient()
	request := cdn.NewPushUrlsCacheRequest()
	request.Urls = common.StringPtrs(urls)
	request.Area = common.StringPtr("global")
	response, err := client.PushUrlsCache(request)
	if _, ok := err.(*errors.TencentCloudSDKError); ok {
		logrus.WithFields(logrus.Fields{
			"error": err.Error(),
		}).Error("An API error has returned")
		return err
	}
	if err != nil {
		logrus.WithFields(logrus.Fields{
			"error": err.Error(),
		}).Panic("Failed to push URLs cache")
	}
	logrus.WithFields(logrus.Fields{
		"response": response.ToJsonString(),
	}).Info("Successfully pushed URLs cache")
	return nil
}
